package com.globaldom.web;

import java.util.HashMap;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.CivResource;
import com.globaldom.model.Person;
import com.globaldom.utils.Constants;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/level")
public class LevelUpController {
	public LevelUpController() {
	}

	@RequestMapping(value = "/upgrade", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> upgradeLevel(HttpSession session, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
			}

		CivResource cv = null;
		// FIXME move this 24 hours queue
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Person person = pm.getObjectById(Person.class, personID);
			int oldlevel = person.getLevel();
			int newlevel = oldlevel + 1;

			cv = pm.getObjectById(CivResource.class, personID +"/" + CivResource.DOLLAR);
			if (cv.getResAvailable() < (oldlevel * 1000)) {
				map.put("level", "" + (oldlevel));
			} else {
				map.put("level", "" + (newlevel));
				person.setLevel(newlevel);
				cv.setResAvailable(cv.getResAvailable() - (oldlevel * 1000));

			}
			map.put(Constants.STATUS, "+OK");
		} catch (Exception ex) {
			map.put(Constants.STATUS, "-ERR");
			map.put(Constants.CODE, ex.getMessage());
		} finally {
			pm.close();
		}
		return map;

	}

}
